package javacommon.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import javacommon.interceptor.utl.SysContent;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import com.sjyy.vo.sessionmodel.SessionUser;

public class ControllerInterceptor {

	private final String target = "org.springframework.web.bind.annotation.RequestMapping";
    private boolean isRequestMapping;
    private static Log logcase = LogFactory.getLog("operationLogger");
    
	public Object doSomeThingAround(ProceedingJoinPoint pjp) throws Throwable {
        /*得到拦截的方法*/
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method m = ms.getMethod();
        Annotation[] as = m.getAnnotations();
        
        isRequestMapping = false;
        for(Annotation a : as){
        	if(target.equals(a.annotationType().getName())){
        		isRequestMapping = true;
        		break;
        	}
        }
        
        if(isRequestMapping){
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        	
        	StringBuilder operationInfo = new StringBuilder();
        	operationInfo.append("-----------------------------\r\n");
        	operationInfo.append("["+sdf.format(new Date())+"]");  //记录当前时间
        	
        	SessionUser user = (SessionUser) SysContent.getSession().getAttribute("login");
    		if(user!=null){
                operationInfo.append(user.getUserId()+"-"+user.getUserName());
    		}else
    			operationInfo.append("未登录用户");
        	
    		
        	String controllerName = pjp.getTarget().getClass().getName().toString();
        	String methodName = m.getName();
        	
        	operationInfo.append(" 访问控制器："+controllerName+"  函数："+methodName+"\r\n");
        	operationInfo.append("请求参数为： \r\n");
        	Object[] args = pjp.getArgs();
        	for(Object o : args){
        		if(o!=null)
        			operationInfo.append(o.toString()+",");
        	}
        	
        	logcase.info(operationInfo.toString());
        }
        
        /**
         *权限验证
         */

        Object result = pjp.proceed();
        return result;
    }
}
